package com.pl.dailycollection.study.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName SemaphoreTest
 * @Description: 模拟限流器
 * @Author pl
 * @Date 2019/12/31
 * @Version V1.0
 **/
public class SemaphoreTest {
    //线程池最大线程数
    private static int THREAD_COUNT=30;
    //创建线程池
    private static ExecutorService pool = Executors.newFixedThreadPool(THREAD_COUNT);
    //信号量
    private static Semaphore semaphore = new Semaphore(10);
    //计数
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 30; i++) {
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        count++;
                        System.out.println("this thread name is ==============>"+Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                      //  semaphore.release();
                    }
                }
            });
        }
        pool.shutdown();
        //线程池结束后运行
        while (!pool.awaitTermination(1, TimeUnit.SECONDS)) {
        }
        System.out.println(count);
    }
}
